package com.good.webapi.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;

import com.good.webapi.Models.Audience;
import com.good.webapi.Models.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

@Component
public class LoginUserArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private Audience audience;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Class<?> clazz = parameter.getParameterType();
        return clazz== TokenUser.class;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = request.getHeader("Authorization");
        String userId;
        try {
            userId = JWT.decode(token).getIssuer();
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(audience.getSecretKey())).withIssuer(userId).build();
            DecodedJWT jwt = verifier.verify(token);
            TokenUser tokenUser = new TokenUser();
            tokenUser.setUserId(Long.valueOf(userId));
            tokenUser.setNickName(jwt.getClaim("data").asString());
            return tokenUser;

        } catch (JWTDecodeException | TokenExpiredException j ) {
            throw new MyException(401,j.getMessage());
//            return  null;
        }
        // 然后根据token获取用户登录信息，这里省略获取用户信息的过程，随便填写一些数据

    }
}
